{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "# make it work in both python2 both python3\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "# skip https auth\n",
    "import ssl\n",
    "\n",
    "ssl._create_default_https_context = ssl._create_unverified_context\n",
    "\n",
    "# 申请地址https://login.bce.baidu.com/reg.html?tpl=bceplat&amp;from=portal，\n",
    "# 进入后先购买（0元）https://cloud.baidu.com/product/nlp_basic中的功能，\n",
    "# 然后新建应用，即可获得API_KEY和SECRET_KEY。\n",
    "\n",
    "API_KEY = '更换为自己申请的内容'\n",
    "\n",
    "SECRET_KEY = '更换为自己申请的内容'\n",
    "\n",
    "COMMENT_TAG_URL = \"https://aip.baidubce.com/rpc/2.0/nlp/v2/comment_tag\"\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'\n",
    "\"\"\"\n",
    "    get token\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {\n",
    "        'grant_type': 'client_credentials',\n",
    "        'client_id': API_KEY,\n",
    "        'client_secret': SECRET_KEY\n",
    "    }\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print(err)\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    result = json.loads(result_str)\n",
    "\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not 'brain_all_scope' in result['scope'].split(' '):\n",
    "            print('please ensure has check the  ability')\n",
    "            exit()\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        print('please overwrite the correct API_KEY and SECRET_KEY')\n",
    "        exit()\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "    call remote http server\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def make_request(url, comment):\n",
    "    print(\"---------------------------------------------------\")\n",
    "    print(\"评论文本：\")\n",
    "    print(\"    \" + comment)\n",
    "    print(\"\\n评论观点：\")\n",
    "\n",
    "    response = request(\n",
    "        url,\n",
    "        json.dumps({\n",
    "            \"text\": comment,\n",
    "            # 5 为旅游类型评论，其他类别评论请参考 https://ai.baidu.com/docs#/NLP-Apply-API/09fc895f\n",
    "            \"type\": 5\n",
    "        }))\n",
    "\n",
    "    data = json.loads(response)\n",
    "\n",
    "    if \"error_code\" not in data or data[\"error_code\"] == 0:\n",
    "        for item in data[\"items\"]:\n",
    "            # 积极的评论观点\n",
    "            if item[\"sentiment\"] == 2:\n",
    "                print(u\"    积极的评论观点: \" + item[\"prop\"] + item[\"adj\"])\n",
    "            # 中性的评论观点\n",
    "            if item[\"sentiment\"] == 1:\n",
    "                print(u\"    中性的评论观点: \" + item[\"prop\"] + item[\"adj\"])\n",
    "            # 消极的评论观点\n",
    "            if item[\"sentiment\"] == 0:\n",
    "                print(u\"    消极的评论观点: \" + item[\"prop\"] + item[\"adj\"])\n",
    "    else:\n",
    "        # print error response\n",
    "        print(response)\n",
    "\n",
    "    # 防止qps超限\n",
    "    time.sleep(0.5)\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "    call remote http server\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def request(url, data):\n",
    "    req = Request(url, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        if (IS_PY3):\n",
    "            result_str = result_str.decode()\n",
    "        return result_str\n",
    "    except URLError as err:\n",
    "        print(err)\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "\n",
    "    # 以下内容可更改。\n",
    "\n",
    "    comment1 = \"最先看一个数字电影+球幕电影，已经让你想要进去一览莫高窟的真容。然后后面再遇到一个好的讲解员能让你爱上莫高窟。正常238的门票是看八个窟的，有三个窟是必看的，其他五个由讲解员随机选择，他们随身都带着钥匙的。正常游览结束后，资料馆里买了两本书，美术馆里参观了一些历史介绍 每天还有两场特窟参观 ，12:00和14:30 ，一共8个特窟，票价是200/人/窟，想看可以选择看哪个，每场四个窟，如果讲解员先看的不是你选的，你需要在等一会 ，所以时间充裕且有兴趣的可以考虑。特窟的意思就是保存更完整，或者特别一些，具有更高的历史价值，另外讲解员会讲的更细致一些。特窟每天都是限流50人的。 我选择了一个45号窟，确实保存更好，但除此之外对于外行的我们没太多特别，也没有数字影响展示出来的高大和艳丽。另外往摆渡车方向去的研学院里还有几个一比一的复刻窟，有几个特窟在此都有复刻版，不想花钱的也可以选择在这看，但缺少讲解员大多看了个寂寞。\"\n",
    "    comment2 = \"山上在种些树就更好了\"\n",
    "    comment3 = \"大气，就是没有独特的解说词了，又点遗憾。[捂脸][捂脸][捂脸]\"\n",
    "\n",
    "    # get access token\n",
    "    token = fetch_token()\n",
    "\n",
    "    # concat url\n",
    "    url = COMMENT_TAG_URL + \"?charset=UTF-8&access_token=\" + token\n",
    "\n",
    "    make_request(url, comment1)\n",
    "    make_request(url, comment2)\n",
    "    make_request(url, comment3)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
